package com.xu.modules.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xu.common.consts.XuConst;
import com.xu.common.utils.RedisCache;
import com.xu.modules.entity.TagEntity;
import com.xu.modules.mapper.TagMapper;
import com.xu.modules.service.TagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xu.modules.service.bo.TagBo;
import com.xu.modules.service.vo.TagVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章标签 服务实现类
 * </p>
 *
 * @author xu
 * @since 2022-07-21
 */
@Service
@RequiredArgsConstructor
public class TagServiceImpl extends ServiceImpl<TagMapper, TagEntity> implements TagService {
    private final TagMapper tagMapper;


    @Override
    public void addByArticleId(List<String> tagList, Long articleId) {
        if(CollectionUtils.isEmpty(tagList)){
            return;
        }
        for (String tagName : tagList) {
            TagEntity tagEntity = new TagEntity();
            tagEntity.setArticleId(articleId);
            tagEntity.setTagName(tagName);
            tagMapper.insert(tagEntity);
        }

    }

    @Override
    public void deleteByArticleId(Long articleId) {
        LambdaQueryWrapper<TagEntity> lqw = Wrappers.lambdaQuery();
        lqw.eq(TagEntity::getArticleId, articleId);
        tagMapper.delete(lqw);
    }

    @Override
    public List<String> listByArticleId(Long articleId) {
        LambdaQueryWrapper<TagEntity> lqw = Wrappers.lambdaQuery();
        lqw.eq(TagEntity::getArticleId, articleId);
        List<TagEntity> tagEntityList = tagMapper.selectList(lqw);
        // 若为空
        if(CollectionUtils.isEmpty(tagEntityList)){
            return new ArrayList<>();
        }
        return tagEntityList.stream().map(TagEntity::getTagName).collect(Collectors.toList());
    }

    @Override
    public void add(TagBo tagBo) {
        TagEntity tagEntity = BeanUtil.copyProperties(tagBo, TagEntity.class);
        // 插入数据库
        tagMapper.insert(tagEntity);
    }


}
